﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Test1
{
    public partial class Form3 : Form
    {
        private int count = 1;
        public Form3()
        {
            DragDrop += Form1_DragDrop;
            DragEnter += Form1_DragEnter;
            Load += Form3_Load;
            InitializeComponent();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            this.AllowDrop = true;
            //窗体自身支持接受拖拽来的控件
        }

        private void button1_DragEnter(object sender, DragEventArgs e)
        { }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            //当Button被拖拽到WinForm上时候，鼠标效果出现
            if ((e.Data.GetDataPresent(typeof(Button))))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void button1_DragDrop(object sender, DragEventArgs e)
        { }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            //拖放完毕之后，自动生成新控件
            Button btn = new Button();
            btn.Size = Button1.Size;
            btn.Location = this.PointToClient(new Point(e.X, e.Y));
            //用这个方法计算出客户端容器界面的X，Y坐标。否则直接使用X，Y是屏幕坐标
            this.Controls.Add(btn);
            btn.Text = "按钮" + count.ToString();
            count = count + 1;
        }

        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            //左键的话，标志位为true（表示拖拽开始）
            if ((e.Button == System.Windows.Forms.MouseButtons.Left))
            {
                Button1.DoDragDrop(Button1, DragDropEffects.Copy | DragDropEffects.Move);
                //形成拖拽效果，移动+拷贝的组合效果
            }
        }
    }
}
